﻿using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Profiling;
#if UNITY_EDITOR
using LZX.MEditor.Enum;
#endif

namespace LZX.Main.HotUpdate.ResourceData
{
#if LZXDebug
    [System.Serializable]
#endif
    public class BundleData
    {
         /// <summary>
            /// 被引用次数
            /// </summary>
            public int Count;
            public AssetBundle Bundle;
            public BundleData(AssetBundle bundle)
            {
                Bundle = bundle;
            }
            public async UniTask<T> LoadAssetAsync<T>(string assetName) where T : UnityEngine.Object
            {
                Count++;
                var bundleReq = Bundle.LoadAssetAsync(assetName);
                await bundleReq;
                var asset = bundleReq.asset as T;
                asset.name = assetName;
#if UNITY_EDITOR
                if (!LoadStatuHelper.LoadedBundles.ContainsKey(Bundle.name))
                {
                    LoadStatuHelper.LoadedBundles.Add(Bundle.name, this);
                    LoadStatuHelper.LoadedAssets.Add(assetName
                        , new AssetData()
                        {
                            count = 1,
                            size = Profiler.GetRuntimeMemorySizeLong(asset)
                        });
                }
                else
                {
                    if (LoadStatuHelper.LoadedAssets.TryGetValue(assetName, out var assetData))
                    {
                        assetData.count++;
                        assetData.size += Profiler.GetRuntimeMemorySizeLong(asset);
                    }
                    else
                    {
                        LoadStatuHelper.LoadedAssets.Add(assetName
                            , new AssetData()
                            {
                                count = 1,
                                size = Profiler.GetRuntimeMemorySizeLong(asset)
                            });
                    }
                }
                LoadStatuHelper.OnLoadAsset?.Invoke(Bundle.name, assetName);
#endif
                return asset;
            }
            public void UnLoadAsset(UnityEngine.Object obj)
            {
                Count--;
                UnityEngine.Object.Destroy(obj);
#if UNITY_EDITOR
                LoadStatuHelper.LoadedAssets.Remove(obj.name);
                LoadStatuHelper.OnUnLoadAsset?.Invoke(Bundle.name, obj.name);
#endif
            }
            public void Unload(bool UnloadUnloadedAssets)
            {
                Bundle.Unload(UnloadUnloadedAssets);
#if UNITY_EDITOR
                LoadStatuHelper.OnUnLoadBundle?.Invoke(Bundle.name, UnloadUnloadedAssets);
                LoadStatuHelper.LoadedBundles.Remove(Bundle.name);
#endif
            }
    }
}